﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using DirectUI.Mobile.UI.Controls;
using RecorderSample.Controller;
using System.Net;
using System.IO;
namespace RecorderSample.View
{
  public   class AudioItem:DirectUIPanel
    {
   // private AudioItemListPageControler _controler = new AudioItemListPageControler();
      private DirectUIButton _btStatus;
      private DirectUILabel _lbTitle;
      private DirectUILabel _lbState;
      private DirectUIButton _btUpload;
      private DirectUIButton _btDelete;
      public event EventHandler ExpandEvent;
      public void OnExpand(EventArgs e)
      {
          if (ExpandEvent != null)
          {
              ExpandEvent(this, e);
          }
      }
      public AudioItem()
          : base()
      {
          this.Height = 57;
          this.Width = 234;
        //  this.BackGroundImage = Resource.AudioMiddle;
          this.BackColor = Color.FromArgb(6, 139, 204);
          this.GradientFill = true;
          this.GradientFillOffset = 20;
          this.Alpha = 200;
          this.EnableDoubleBuffer = true;
          _lbTitle = new DirectUILabel();
          _lbTitle.Click += new EventHandler(_lbTitle_Click);
          _lbTitle.ForeColor = Color.Yellow;
          _lbTitle.Width = 204;
          _lbTitle.Height = 20;
          _lbTitle.Left = 5;
          _lbTitle.Top = 0;
          _btStatus = new DirectUIButton();
          _btStatus.Width = 16;
          _btStatus.Left = 210;
          _btStatus.Height = 16;
          _btStatus.Top = 0;
          _btStatus.Shape = ButtonShape.Flat;
          _btStatus.Image = Resource.mbi_028;
          _lbState = new DirectUILabel();
          _lbState.Top = 23;
          _lbState.Left = 5;
          _lbState.Width = 100;
          _lbState.Height = 20;
          _lbState.Text = "未上传......";
         // _lbState.Font = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);
          _lbState.ForeColor = Color.White;
          _btUpload = new DirectUIButton();
          _btUpload.Shape = ButtonShape.Flat;
          _btUpload.Image = Resource.AudioUpload;
          _btUpload.Width = 67;
          _btUpload.Height = 16;
          _btUpload.Left = 100;
          _btUpload.Top = 23;
          _btUpload.Click += new EventHandler(_btUpload_Click);
          _btDelete = new DirectUIButton();
          _btDelete.Shape = ButtonShape.Flat;
          _btDelete.Image = Resource.AudioDelete;
          _btDelete.Width = 67;
          _btDelete.Left = 170;
          _btDelete.Top = 23;
          _btDelete.Height = 16;
          _btDelete.Click += new EventHandler(_btDelete_Click);
      //    _btDelete.Command = "Delete";
          this.Controls.Add(_lbTitle);
          this.Controls.Add(_lbState);
          this.Controls.Add(_btDelete);
          this.Controls.Add(_btUpload);
          this.Controls.Add(_btStatus);
          _progressTimer = new System.Windows.Forms.Timer();
          _progressTimer.Interval = 200;
          _progressTimer.Enabled = false;
          _progressTimer.Tick += new System.EventHandler(_progressTimer_Tick);
      }

      void _btDelete_Click(object sender, EventArgs e)
      {
          ((AudioItemListPage)PageManager.Instance.Pages["AudioList"]).DeleteItem(this);
      }

      //void _btDelete_Click(object sender, EventArgs e)
      //{
        
      //}
      private void _progressTimer_Tick(object sender, System.EventArgs e)
      {
          if (_byteUploaded == 0 && _state == 0)
          {
              if (_lbState.Text.Length >= 5)
              {
                  if (_lbState.Text[_lbState.Text.Length - 5] == '.')
                  {
                      _lbState.Text = "正在连接.";
                  }
                  else if (_lbState.Text[_lbState.Text.Length - 4] == '.')
                  {
                      _lbState.Text = "正在连接.....";
                  }
                  else if (_lbState.Text[_lbState.Text.Length - 3] == '.')
                  {
                      _lbState.Text = "正在连接....";
                  }
                  else if (_lbState.Text[_lbState.Text.Length - 2] == '.')
                  {
                      _lbState.Text = "正在连接...";
                  }
                  else if (_lbState.Text[_lbState.Text.Length - 1] == '.')
                  {
                      _lbState.Text = "正在连接..";
                  }
              }
              TimeSpan ts = DateTime.Now - _beginTime;
              if (ts.Seconds > 0)
              {
                  _byteRate = (ByteUploaded - _lastbyteUploaded) / 1024;
                  if (_byteRate < 0)
                  {
                      _byteRate = 0;
                  }
                  _lastbyteUploaded = ByteUploaded;
                  if (_byteRate > 0)
                  {
                      _lbState.Text = _byteRate.ToString() + "K/秒";
                  }
          }
     
          }

      }
      private string _upLoadUrl = "http://61.134.84.164/GSTS_Portal/";
      void _btUpload_Click(object sender, EventArgs e)
      {

        //  _btUpload.Enabled = false;
     //     string url=MPS.Device.Common.ConfigFactory.getInstance().GetConfig(
    //   BeginUpload(
          FileInfo info = new FileInfo(FileName);

          BeginUpload(_upLoadUrl + "/tempUpload/" + info.Name);
      }

      void _lbTitle_Click(object sender, EventArgs e)
      {
          if (this.Height == 20)
          {
              Expand();
          }
          else
          {
              Minimize();
          }
        
      }
      public string FileName { get; set; }
      public string Title
      {
          get
          {
              return _lbTitle.Text;
          }set{
              _lbTitle.Text = value;
          }
      }
      public void Minimize()
      {
          _lbTitle.ForeColor = Color.White;
          _btUpload.Visible = false;
          _btDelete.Visible = false;
          _lbState.Visible = false;
   //       this.BackGroundImage = null;
          this.BackColor = Color.Transparent;
          this.GradientFill = false;
          this.EnableDoubleBuffer = false;
         this.Alpha = 255;
          this.Height = 20;
      
      }
      //public void Play()
      //{
      //    _controler.Play(FileName);
      //}
      //public void Stop()
      //{
      //    _controler.Stop();
      //}
      public void Expand()
      {
          _lbTitle.ForeColor = Color.Yellow;
          _btUpload.Visible = true;
          _btDelete.Visible = true;
          _lbState.Visible = true;
      //    this.BackGroundImage = Resource.AudioMiddle;
          this.Height = 57;
          this.BackColor = Color.FromArgb(2, 70, 177);
          this.GradientFill = true;
          this.GradientFillOffset = 20;
         this.EnableDoubleBuffer = true;
          this.Alpha = 200;
          OnExpand(null);
      }
      private HttpWebRequest request;
      private bool _mask = true;
      private bool _isCancel = true;
 
      private string _temFile;
      private bool _outOfMemory;
      private string _updateString;
      private int _state = -1;
      private System.Windows.Forms.Timer _progressTimer;
      private string _url;
      private double _byteUploaded;
      public double ByteUploaded
      {
          get
          {
              return _byteUploaded;
          }
      }
      private double _fileLength;
      public double FileLength
      {
          get
          {
              return _fileLength;
          }
      }

      public int State
      {
          get
          {
              return _state;
          }
      }
      private DateTime _beginTime;
      private double _byteRate;
      private double _lastbyteUploaded = 0;
      public void BeginUpload(string url)
      {
          _progressTimer.Enabled = true;
          _url = url;
          _state = 0;
          _byteUploaded = 0;
          _lastbyteUploaded = 0;
          _byteRate = 0;
          _mask = true;
          _beginTime = DateTime.Now;
          _lbState.Text = "正在连接.";
          this._isCancel = false;
          request = (HttpWebRequest)WebRequest.Create(url);
          request.Method = "PUT";
          request.SendChunked = true;
          request.Timeout = 200000;
          request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);

      }
      public delegate void UpdateStatusDelegate(double byteUploaded, int state);
      public event UpdateStatusDelegate UploadProgressChanged;

      protected void OnUploadProgressChanged(double byteUploaded, int state)
      {
          _byteUploaded = byteUploaded;
          if (state == 0)
          {
              _updateString = ((int)_byteUploaded / 1024).ToString() + "/" + ((int)_fileLength / 1024).ToString() + " K";
          }
          else if (state == 1)
          {

              _mask = false;


              _updateString = "上传成功";
              //pictureBox1.Image = Resource.uploadChedcked;
              Refresh();
          }
          else if (state == -1)
          {
              _updateString = "已取消";
              Cancel();
          }
          else if (state == 2)
          {
            //  pictureBox1.Image = Resource.uploadtry;
              this._isCancel = true;
          }
       //   _lbState.Text = _updateString;
          _lbState.Text = _updateString;
          if (UploadProgressChanged != null)
          {
              UploadProgressChanged(byteUploaded, state);
          }
          // this.Invalidate(new Rectangle(0, this.Height / 2 - 10, this.Width, 10));
      }
      private void ReadCallback(IAsyncResult asynchronousResult)
      {
          HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
          //  string temFileName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\"+DateTime.Now.Ticks.ToString();
          //  _temFile = temFileName;
          // End the operation.
          Stream postStream = null;
          FileStream fs = null;
          string temFileName = FileName;
          try
          {

              //  File.Copy(_imageFileName, temFileName);
              fs = new FileStream(temFileName, FileMode.Open);
              postStream = request.EndGetRequestStream(asynchronousResult);
              // Convert the string into a byte array.
              byte[] byteArray = new byte[1024];
              _fileLength = fs.Length;
              double byteReaded = 0;
              int readed = fs.Read(byteArray, 0, 1024);
              _state = 0;

              while (readed > 0)
              {
                  byteReaded += readed;
                  // Write to the request stream.
                  postStream.Write(byteArray, 0, readed);

                  if (((System.Windows.Forms.Control)this.Host).InvokeRequired)
                  {
                      if (_isCancel)
                      {
                          _state = -1;
                          fs.Close();
                          fs = null;
                          request.Abort();

                      }
                      //通过此种方式切换到当前工作线程
                      ((System.Windows.Forms.Control)this.Host).Invoke(new UpdateStatusDelegate(OnUploadProgressChanged),
                                  new object[] { byteReaded, _state });
                      if (_isCancel)
                      {
                          break;
                      }
                  }
                  readed = fs.Read(byteArray, 0, 1024);
              }
              fs.Close();
              fs = null;
              if (!_isCancel)
              {
                  postStream.Close();
                  WebResponse res = request.GetResponse();
                  res.Close();
              }
              _state = 1;
              ((System.Windows.Forms.Control)this.Host).Invoke(new UpdateStatusDelegate(OnUploadProgressChanged),
                              new object[] { byteReaded, _state });
              //  File.Delete(temFileName);
          }
          catch (Exception ex)
          {
              request.Abort();
              _state = 2;
              _updateString = "上传失败，请重试";
              ((System.Windows.Forms.Control)this.Host).Invoke(new UpdateStatusDelegate(OnUploadProgressChanged),
                                new object[] { 0, _state });


          }
          finally
          {
              if (postStream != null)
              {
                  postStream.Close();
              }
              if (fs != null)
              {
                  fs.Close();
              }


          }
      }
      public void Cancel()
      {
          _isCancel = true;
          _state = -1;
          if (this.FileLength != this.ByteUploaded && this.FileLength > 0)
          {
            //  pictureBox1.Image = Resource.uploadtry;
          }
          else
          {
            //  pictureBox1.Image = Resource.uploaduchecked;

          }
      }
    }
}
